/*  
 * i-OSGi - Tunable Bundle Isolation for OSGi
 * Copyright (C) 2011  Sven Schulz
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.iosgi.outpost.util.ipr;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Sven Schulz
 */
public class Registry implements Runnable {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(Registry.class);

	public static Registry getRegistry() {
		return REGISTRY;
	}

	private static Registry REGISTRY;
	static {
		try {
			REGISTRY = new Registry();
		} catch (SocketException se) {
			LOGGER.error("failed to create IPR registry");
		}
	}

	private DatagramSocket socket;
	private Thread t;
	private final Map<MacAddress, InetAddress> ipByMac;

	private Registry() throws SocketException {
		ipByMac = new HashMap<MacAddress, InetAddress>();
		socket = new DatagramSocket(2505);
		t = new Thread(this);
		t.start();
	}

	public MacAddress get(InetAddress addr) {
		for (Map.Entry<MacAddress, InetAddress> e : ipByMac.entrySet()) {
			if (e.getValue().equals(addr)) {
				return e.getKey();
			}
		}
		return null;
	}

	public InetAddress get(MacAddress mac) {
		return ipByMac.get(mac);
	}

	public InetAddress get(MacAddress mac, long timeout, TimeUnit unit)
			throws InterruptedException, TimeoutException {
		long deadline = System.currentTimeMillis()
				+ TimeUnit.MILLISECONDS.convert(timeout, unit);
		InetAddress addr = null;
		while (addr == null) {
			if (System.currentTimeMillis() > deadline)
				throw new TimeoutException();
			synchronized (ipByMac) {
				addr = ipByMac.get(mac);
				if (addr == null) {
					ipByMac.wait(deadline - System.currentTimeMillis());
				}
			}
		}
		return addr;
	}

	@Override
	public void run() {
		byte[] buf = new byte[65536];
		DatagramPacket p = new DatagramPacket(buf, buf.length);
		while (!Thread.interrupted()) {
			try {
				socket.receive(p);
				IPRPacket iprp = IPRPacket.fromDatagram(p);
				synchronized (ipByMac) {
					ipByMac.putAll(iprp.getAll());
					ipByMac.notifyAll();
				}
			} catch (Exception e) {
				LOGGER.error("failed to process incoming UDP packet", e);
			}
		}
	}

}